package me.zhengjie.demo.rest;

import me.zhengjie.aop.log.Log;
import me.zhengjie.demo.domain.Demo;
import me.zhengjie.demo.service.DemoService;
import me.zhengjie.demo.service.dto.DemoQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @author ZhengGuozhen
* @date 2020-04-10
*/
@Api(tags = "demo管理")
@RestController
@RequestMapping("/api/demo")
public class DemoController {

    private final DemoService demoService;

    public DemoController(DemoService demoService) {
        this.demoService = demoService;
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('demo:list')")
    public void download(HttpServletResponse response, DemoQueryCriteria criteria) throws IOException {
        demoService.download(demoService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询demo")
    @ApiOperation("查询demo")
    @PreAuthorize("@el.check('demo:list')")
    public ResponseEntity<Object> getDemos(DemoQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(demoService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增demo")
    @ApiOperation("新增demo")
    @PreAuthorize("@el.check('demo:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Demo resources){
        return new ResponseEntity<>(demoService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改demo")
    @ApiOperation("修改demo")
    @PreAuthorize("@el.check('demo:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Demo resources){
        demoService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除demo")
    @ApiOperation("删除demo")
    @PreAuthorize("@el.check('demo:del')")
    @DeleteMapping
    public ResponseEntity<Object> deleteAll(@RequestBody Integer[] ids) {
        demoService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}